var React = require('react');

var Post = React.createClass({
  getInitialState: function () {
    return {
      id: $.getQuery('id'),
      post: {},
      comments: []
    };
  },

  componentDidMount: function () {
    $.getJSON(baseUrl + "getTextAndCommentByTextId/" + this.state.id, function (result, status) {
      console.log(result.data[0].comments);
      if (this.isMounted()) {
        this.setState({
          post: result.data[0],
          comments: result.data[0].comments
        });
      }
    }.bind(this));
  },

  handleNewReply: function (replyToUser, inputId) {
    this.newComment(replyToUser, inputId);
  },

  handleNewComment: function () {
    this.newComment();
  },

  newComment: function (replyToUser, inputId) {
    var toUserId = replyToUser ? replyToUser.id : -1;
    var postId = this.state.id;

    var comment = inputId ? document.getElementById(inputId).value : $('#comment-box').val();
    if ($.isBlank(comment)) {
      console.log("return");
      return;
    }

    var url = baseUrl + "postComment/" + postId + "/" + toUserId + "/" + comment;
    $.getJSON(url, function (result, status) {
// console.log(result.data);
      if (this.isMounted()) {
        this.setState({
          comments: result.data
        });
      }
    }.bind(this));
  },

  render: function () {
    return (
      <div className="post">
        <div className="devide-title">
          <h1>{this.state.post.title}</h1>
        </div>
        <p className="post-content">{this.state.post.text}</p>
        <div>
          <div className="devide-title">
            <h1>评论</h1>
          </div>
          <div className="comment-list">
            {this.state.comments.map(function (e) {
          var inputId = 'inline-comment-box-' + e.id;
          return (
              <div className="comment" key={e.id}>
                <div className="comment-image">
                  <img alt="Logo image" src="avatar.png"/>
                </div>
                <div className="comment-content">
                  <h1>{e.from.username}</h1>
                  <p>{e.comment}</p>
                  <div className="inline-comment">
                    <input id={inputId} placeholder="说点什么" type="text"/>
                    <input onClick={this.handleNewReply.bind(this, e.from, inputId)} type="button" value="发表"/>
                  </div>
                </div>
              </div>
          )
        }, this)}
          </div>
          <div className="new-comment">
            <textarea id="comment-box" placeholder="留下你的评论"/>
            <input id="comment-button" onClick={this.handleNewComment} type="button" value="发表"/>
          </div>
        </div>
      </div>
    );
  }
});

module.exports = Post;
